﻿using AutoMapper;
using MediatR;
using S.BreedingHistory.Domain.Model;
using S.BreedingHistory.Infrastructure.Interface;
using S.BreedingHistory.Read.Api.Application.Command;
using S.BreedingHistory.Read.Api.Dto;
using System.Collections.Generic;

namespace S.BreedingHistory.Read.Api.Application.CommandHandler
{
    public class BreedingHistoryListCommandHandler : IRequestHandler<BreedingHistoryListCommand, BreedHistoryPageListDto>
    {
        private readonly IBreedingHistoryRepository breedingHistoryRepository;
        private readonly IMapper mapper;

        public BreedingHistoryListCommandHandler(IBreedingHistoryRepository breedingHistoryRepository,IMapper mapper)
        {
            this.breedingHistoryRepository = breedingHistoryRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 种母历史记录的显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BreedHistoryPageListDto> Handle(BreedingHistoryListCommand request, CancellationToken cancellationToken)
        {
            List<BreedingHistoryModel> breedingHistoryList =(await breedingHistoryRepository.GetAllAsync()).Where(m=>m.IsDel==true).OrderByDescending(m=>m.CreateDate).ToList();
            if (!string.IsNullOrEmpty(request.BreedingId))
            {
                breedingHistoryList= breedingHistoryList.Where(m=>m.EarTag==request.BreedingId).ToList();
            }
            if (!string.IsNullOrEmpty(request.sDate))
            {
                breedingHistoryList = breedingHistoryList.Where(m => m.BreedingDate >= DateTime.Parse(request.sDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.eDate))
            {
                breedingHistoryList = breedingHistoryList.Where(m => m.BreedingDate < DateTime.Parse(request.eDate).AddDays(1)).ToList();
            }
            List<BreedingHistoryListDto> breedingHistoryListDtos = new List<BreedingHistoryListDto>();
            foreach (var item in  breedingHistoryList)
            {
                BreedingHistoryListDto breedingHistoryListDto = mapper.Map<BreedingHistoryListDto>(item);
                breedingHistoryListDtos.Add(breedingHistoryListDto);
            }
            int totalCount = breedingHistoryListDtos.Count;
            int pageCount = (int)Math.Ceiling((totalCount*1.0)/request.pageSize);
            breedingHistoryListDtos = breedingHistoryListDtos.Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            BreedHistoryPageListDto breedHistoryPageListDto = new BreedHistoryPageListDto()
            {
                totalCount = totalCount,
                pageCount = pageCount,
                BreedingHistoryList = breedingHistoryListDtos
            };
            return breedHistoryPageListDto;
        }
    }
}
